package com.tianqu.tms.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author liudianyong
 * 
 */
public class ZIPUtil {

	private ZIPUtil() {
	}

	/**
	 * 创建zip
	 * 
	 * @param filePath  文件集合
	 * @param zipFilePath
	 */
	public File CreateZipFile(List filePath, String zipFilePath) {
		File file= new File(zipFilePath);
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		try {
			if(filePath.size()==0)return null;
			fos = new FileOutputStream(file);
			zos = new ZipOutputStream(fos);
            for(int i=0;i<filePath.size();i++){
            	writeZipFile(new File((String) filePath.get(i)), zos, "");
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		finally {
			try {
				if (zos != null)
					zos.close();
				if (fos != null)
					fos.close();

			} catch (IOException e) {
				e.printStackTrace();

			}
		}
		
		return file;

	}

	/**
	 * 写入zip文件
	 * 
	 * @param f
	 * @param zos
	 * @param hiberarchy
	 */
	private void writeZipFile(File f, ZipOutputStream zos, String hiberarchy) {
		if (f.exists()) {
			if (f.isDirectory()) {
				hiberarchy += f.getName() + "/";
				File[] fif = f.listFiles();
				for (int i = 0; i < fif.length; i++) {
					writeZipFile(fif[i], zos, hiberarchy);
				}

			} else {
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(f);
					ZipEntry ze = new ZipEntry(hiberarchy + f.getName());
					zos.putNextEntry(ze);
					byte[] b = new byte[1024];
					while (fis.read(b) != -1) {
						zos.write(b);
						b = new byte[1024];
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (fis != null)
							
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
		}

	}

	private static ZIPUtil zu = null;

	public static ZIPUtil getInstance() {
		if (zu == null)
			zu = new ZIPUtil();
		return zu;

	}

	public static void main(String[] args) {
       
		
		
	}

}